package com.example.deepschool.service.Order;

import com.example.deepschool.Model.User;
import com.example.deepschool.exception.CustomException;
import com.example.deepschool.repositories.OrderRepository;
import com.example.deepschool.util.PermissionsControl;
import com.example.deepschool.util.Redis;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

@Service
public class OrderImpl implements Order {
	
	private final OrderRepository orderRepository;
	
	public OrderImpl (OrderRepository orderRepository) {
		this.orderRepository = orderRepository;
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Order insert (com.example.deepschool.Model.Order order,String UUID) {
		try {
			User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
			if(!PermissionsControl.VERIFY_JOIN_COURSE(user.getPermissions())){
				throw new RuntimeException("账号没有权限加入课程.");
			}
			order.setUserId(user.getId());
			if(order.getTitle()==null){
				throw new RuntimeException("订单标题不能为空.");
			}
			orderRepository.insert(order);
			return orderRepository.selectByUserIdAndCourseId(order);
		} catch (Exception e) {
			throw new CustomException(500, "订单生成失败");
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Order selectById (Long id) {
		try {
			return orderRepository.selectById(id);
		} catch (Exception e) {
			throw new CustomException(500, "订单查询失败");
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Order update (com.example.deepschool.Model.Order order) {
		try {
			int status = orderRepository.update(order);
			if (status == 0) {
				throw new CustomException(400, "订单已超时");
			}
			return orderRepository.selectByUserIdAndCourseId(order);
		} catch (Exception e) {
			throw new CustomException(500, "订单更新失败");
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Order[] selectByPending (String UUID) {
		try {
			User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
			return orderRepository.selectByPending(user.getId());
		} catch (Exception e) {
			throw new CustomException(500, "订单查询失败");
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Order[] selectByPaid (String UUID) {
		try {
			User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
			return orderRepository.selectByPaid(user.getId());
		} catch (Exception e) {
			throw new CustomException(500, "订单查询失败");
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Order[] selectByCancelled (String UUID) {
		try {
			User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
			return orderRepository.selectByCancelled(user.getId());
		} catch (Exception e) {
			throw new CustomException(500, "订单查询失败");
		}
	}
	
	@SneakyThrows
	@Override
	public Integer selectByCourseId (Long courseId) {
		try {
			return orderRepository.selectByCourseId(courseId);
		} catch (Exception e) {
			throw new CustomException(500, "订单查询失败");
		}
	}
}
